/* eslint-disable @next/next/no-img-element */
import { useRouter } from 'next/router'
import * as React from 'react'
import styles from '../styles/Me.module.scss'
import { Button, Dropdown, Form, Input, Menu } from 'antd'
import toast from '../components/Toast'
import * as userService from '../services/user.service'
import { IArticle, IUser } from '../types'
import { GetServerSideProps } from 'next'
import 'antd/dist/antd.css'
import Header from '../components/header'
import ArticleItem from '../components/articleItem'
import IconFont from '../assets/icon'
import * as articleService from '../services/article.service'
import TextArea from 'antd/lib/input/TextArea'
import Follows from '../components/follows'

interface Props {
  user: IUser
  articles: IArticle[]
}

const menu = (
  <Menu>
    <Menu.Item>编辑</Menu.Item>
    <Menu.Item>删除</Menu.Item>
  </Menu>
)

export const getServerSideProps: GetServerSideProps = async ctx => {
  const result = await userService.userInfo(ctx.req.cookies.token)
  const rows = await userService.articles(result.data._id)
  rows.rows.sort((a: IArticle, b: IArticle) => {
    return new Date(b.time).valueOf() - new Date(a.time).valueOf()
  })
  if (result.stat === 'OK') {
    return {
      props: {
        user: result.data,
        articles: rows.rows
      }
    }
  }
  return {
    redirect: {
      destination: '/login',
      permanent: false
    }
  }
}

export default function Me(props: Props) {
  const [area, setArea] = React.useState<string>('articles')
  const [prePwd, setPre] = React.useState<string>('')
  const [newPwd, setNew] = React.useState<string>('')
  const [rows, setRows] = React.useState<IArticle[]>(props.articles)
  const [show, setShow] = React.useState<boolean>(false)
  const [pwd, setPwd] = React.useState<boolean>(false)
  const [nickname, setNickname] = React.useState<string>(props.user.nickname)
  const [introduction, setIntroduction] = React.useState<string>(
    props.user.introduction
  )
  const openBtn = React.useRef<HTMLInputElement>(null)
  const router = useRouter()

  const edit = (id: string) => {
    router.push('/editArticle/' + id)
  }

  const remove = async (id: string) => {
    await articleService.remove(id)
    const res = await userService.articles(props.user._id)
    setRows(res.rows)
    toast('已删除')
  }

  const onOpenChange = async () => {
    let file = openBtn.current?.files
    if (file![0].type.startsWith('image')) {
      await userService.userAvatar(file![0])
      document.getElementById(
        'wrap1'
      )!.style.backgroundImage = `url(/api/article/download/${props.user.avatar})`
      toast('修改成功')
    } else {
      toast('修改失败')
    }
  }

  const onclick = () => {
    openBtn.current?.click()
  }

  const onSetShow = () => {
    setShow(!show)
  }

  const onSetpwd = () => {
    setPwd(!pwd)
  }

  const changePwd = async () => {
    const res = await userService.editPwd(prePwd, newPwd)
    if (res.stat === 'OK') {
      toast('修改成功')
    } else {
      toast(res.message)
    }
    setPwd(!pwd)
  }

  const submit = async () => {
    await userService.edit(nickname, introduction)
    toast('修改成功')
    setShow(!show)
  }

  return (
    <>
      <Header user={props.user} />

      <div className={styles.main}>
        {/* 修改密码 */}
        <Form className={pwd ? styles.form : styles.none}>
          <div className={styles.editTitle}>修改密码</div>
          <Form.Item
            label="原密码"
            className={styles.text}
            rules={[{ required: true, message: '请输入原密码' }]}
          >
            <Input
              type="password"
              className={styles.input}
              onChange={e => setPre(e.target.value)}
            />
          </Form.Item>
          <Form.Item label="新密码" className={styles.text}>
            <Input
              type="password"
              className={styles.input}
              onChange={e => setNew(e.target.value)}
            />
          </Form.Item>
          <Button
            className={styles.btn2}
            size="large"
            onClick={() => {
              setPwd(!pwd)
            }}
          >
            取消
          </Button>
          <Button className={styles.btn2} size="large" onClick={changePwd}>
            确定
          </Button>
        </Form>

        <Form className={show ? styles.form : styles.none}>
          <div className={styles.editTitle}>
            修改个人信息
            <IconFont
              type="icon-guanbi"
              className={styles.close}
              onClick={onSetShow}
            />
          </div>

          <Form.Item label="昵称" className={styles.text}>
            <Input
              className={styles.input}
              value={nickname}
              onChange={e => setNickname(e.target.value)}
            />
          </Form.Item>
          <Form.Item label="个人简介" className={styles.text}>
            <TextArea
              rows={5}
              className={styles.input}
              value={introduction}
              onChange={e => setIntroduction(e.target.value)}
            />
          </Form.Item>
          <Button className={styles.btn3} size="large" onClick={submit}>
            确定修改
          </Button>
        </Form>

        <div className={styles.left}>
          <div className={styles.avatar}>
            <div
              id="wrap1"
              style={{
                height: '100px',
                width: '100px',
                backgroundImage: `url(/api/article/download/${props.user.avatar})`,
                backgroundSize: 'cover'
              }}
            >
              <div id="mask" className={styles.mask} onClick={onclick}>
                <IconFont type="icon-xiangji" className={styles.xiangji} />
              </div>
              <input
                id="input"
                type="file"
                className={styles.none}
                ref={openBtn}
                onChange={() => onOpenChange()}
              />
            </div>
          </div>
          <div className={styles.nickname}>昵称：{props.user.nickname}</div>
          <div className={styles.intro}>
            个人简介：{props.user.introduction}
          </div>
          <Menu
            className={styles.menu}
            selectedKeys={[area]}
            onClick={e => setArea(e.key)}
            mode="vertical"
          >
            <Menu.Item key="articles">我的文章</Menu.Item>
            <Menu.Item key="follows">我的关注</Menu.Item>
          </Menu>
          <Button className={styles.btn} size="large" onClick={onSetShow}>
            编辑个人资料
          </Button>
          <Button
            className={styles.btn}
            size="large"
            onClick={() => router.push('/post')}
          >
            发布文章
          </Button>
          <Button className={styles.btn} size="large" onClick={onSetpwd}>
            修改密码
          </Button>
        </div>

        {/* 关注 */}
        <div className={styles.right}>
          <div className={area === 'articles' ? styles.none : styles.follow}>
            <Follows user={props.user} />
          </div>

          <div className={area === 'articles' ? styles.articles : styles.none}>
            {rows.map((item, index) => {
              return (
                <div className={styles.item} key={index}>
                  <ArticleItem item={item} />
                  <Dropdown
                    overlay={
                      <Menu>
                        <Menu.Item onClick={() => edit(item._id)}>
                          编辑
                        </Menu.Item>
                        <Menu.Item onClick={() => remove(item._id)}>
                          删除
                        </Menu.Item>
                      </Menu>
                    }
                    placement="bottomCenter"
                    arrow
                  >
                    <IconFont type="icon-chilun--" className={styles.icon} />
                  </Dropdown>
                </div>
              )
            })}
          </div>
        </div>
      </div>
    </>
  )
}
